<template>
  <div class="" style="background-color: #f2f4f7;width: 100%;height: 100%">
    <div class="head">
      <span style="padding-bottom: 8px">试卷详情</span>
    </div>


    <!--      试题列表-->
    <div class="examList" v-if="paperData.paperInfo">

      <div class="examList-head">
        <!--        试卷名称及其信息-->
        <div style="padding-left: 37px;padding-top: 35px">
            <span style="  display: flex;font-size: 18px;color: #181E33;font-weight: bold;">
            {{ paperData.paperTitle }}
            </span>
          <!--            v-if="paperData.paperInfo" 防止加载之前报错-->
          <div style="margin-top: 15px;display: flex">
              <span style=" color: #A8A8B3;font-size: 14px;text-align: start!important;">
                题量：{{ paperData.paperQuestionList.length }}
              </span>
            <span style="color: #A8A8B3;font-size: 14px;margin-left: 17px">
                满分：{{
                paperData.paperInfo.singleNum * 5 + paperData.paperInfo.multipleNum * 5 + paperData.paperInfo.fillInNum * 5 + paperData.paperInfo.textNum * 10
              }}
              </span>
          </div>
          <div style="margin-top: 11px;display: flex; justify-content: start">
            <div><span style=" color: #A8A8B3;font-size: 14px; ">
                剩余时间：
              </span></div>
            <div>
              <el-statistic
                  :value-style="valueStyle"
                  :value="new Date(examDataEndTime).getTime()"
                  format="HH:mm:ss"
                  title=""
                  time-indices/>
            </div>
          </div>
        </div>
      </div>

      <!--     试题部分-->
      <div style="width: 90%;text-align: left; margin-top: 70px;margin-left: 35px">
        <!--单选题-->
        <div v-if="singleList.length!=0" style="margin-top: 35px;width: 100%">
          <div style="margin-bottom: 35px">
            <span style="font-size:18px;font-weight: bold;font-family: 宋体;color: #000000">
              一、单选题 (本题共{{ paperData.paperInfo.singleNum }}小题，每小题5分，共{{ paperData.paperInfo.singleNum * 5 }}分)
            </span>
          </div>
          <!--单选题试题列表-->
          <div class="singleList" v-for="(question,index) of singleList">
            <!--索引-->
            <span style="font-size: 19px; line-height: 30px ;font-family: 宋体">{{ index + 1 }}.{{
                question.questionTitle
              }}</span>
            <el-radio-group v-model="question.selected"
                            style="margin-top: 20px;margin-bottom:50px;display: flex;flex-direction: column">
              <el-radio style="display: flex; flex-direction: row; align-items: center;margin-bottom: 25px"
                        v-for="(choice, index) of question.paperQuestionChoiceList" :label="String(index+1)"
                        :key="choice.id">
                <div style=" font-size: 18px;font-family: 宋体 ;margin-left: 10px;">
                  <span>{{ preChoice[index] }}. {{ choice.choiceText }}</span>
                </div>
              </el-radio>
            </el-radio-group>
          </div>
        </div>

        <!--多选题-->
        <div v-if="multiList.length!=0" style="margin-top: 65px ">
          <div>
            <span style="font-size:18px;font-weight: bold;font-family: 宋体;color: #000000">
              二、多选题 (本题共{{ paperData.paperInfo.multipleNum }}小题，每小题5分，共{{ paperData.paperInfo.multipleNum * 5 }}分)
              在每小题给出的选项中，有多项符合题目要求，全部选对的得5分，部分选对的得2分，有选错的不得分。
            </span>
          </div>


          <!--多选题题目列表-->
          <div class="multiList" style="width: 100%;text-align: start; margin-top: 35px"
               v-for="(question, qIndex) of multiList">
            <!--题目标题-->
            <span style="font-size: 19px;font-family: 宋体;">{{ qIndex + 1 }}.{{ question.questionTitle }}</span>

            <!--题目选项-->
            <div style="display: flex; flex-direction: column; font-size: 18px;margin-top: 20px;"
                 v-for="(choice, cIndex) of question.paperQuestionChoiceList">
              <el-checkbox :label="String(cIndex + 1)" v-model="question.selected">
                <div style="font-size: 18px;font-family: 宋体;margin-left: 10px;margin-bottom: 5px;">
                  <span>{{ preChoice[cIndex] }}. {{ choice.choiceText }}</span>
                </div>
              </el-checkbox>
            </div>
            <div style="margin-bottom: 60px"></div>
          </div>

        </div>

        <!--        填空题-->
        <div v-if="fillInList.length!=0" style="width: 100%;text-align: start; margin-top: 65px ">

          <div>
            <span style="font-size:18px;font-weight: bold;font-family: 宋体;color: #000000">
              三、填空题：本题共{{ paperData.paperInfo.fillInNum }}小题，每小题5分，共{{ paperData.paperInfo.fillInNum * 5 }}分。
              错误则不得分。
            </span>
          </div>

          <div class="fillInList" style="width: 100%;text-align: start; margin-top: 35px"
               v-for="(question,index) of fillInList">
            <!--题目标题-->
            <span style="font-size: 19px;font-family: 宋体;">{{ index + 1 }}.{{ question.questionTitle }}</span>

            <!--答案输入框-->
            <div style="display: flex;flex-wrap: wrap; font-size: 18px;margin-top: 15px;margin-bottom: 90px">
              <div v-for="(answer, index) of question.paperQuestionAnswerList" :label="index + 1">
                <div class="inputDeep" style="display: flex;margin-left: 30px;">
                  <span style="margin-top: 20px">{{ index + 1 }}.</span>
                  <el-input class="input_bottom" style="width: 200px!important;" v-model="question.selected[index]"/>
                </div>
              </div>
            </div>

          </div>

        </div>

        <!--简答题-->
        <div v-if="textList.length!=0" style="margin-top: 65px ">
          <div style="width: 100%;text-align: start; margin-top: 65px ">
            <span style="font-size:18px;font-weight: bold;font-family: 宋体;color: #000000">
              四、简答题：本题共{{ paperData.paperInfo.textNum }}小题，每小题10分，共{{ paperData.paperInfo.textNum * 10 }}分。
            </span>
          </div>
          <!--简答题题目列表-->
          <div class="textList" style="width: 100%;text-align: start; margin-top: 35px"
               v-for="(question,index) of textList">
            <!--题目标题-->
            <!--String.fromCharCode(index + 65)  用于建立索引-->
            <span style="display: none">{{ String.fromCharCode(index + 65) }}</span>
            <span style="font-size: 19px;font-family: 宋体;">{{ index + 1 }}.{{ question.questionTitle }}</span>
            <div style="display: flex; font-size: 18px; margin-top: 15px; margin-bottom: 100px; width: 500px;">
              <el-input type="textarea" :rows="7" v-model="question.selected"></el-input>
            </div>
          </div>
        </div>
        <!--        美化布局-->
        <div style="height: 15px"></div>
      </div>


    </div>

    <!--  lex-wrap: wrap 自动换行-->
    <!--    悬浮导航栏-->
    <div class="examMenu" v-if="paperData.paperInfo">

      <!-- 单选题标题-->
      <div v-if="singleList.length!=0">
        <div
            style="overflow-y: auto;margin-top: 10px;margin-left:20px;width: 100%; height: 40px; display: flex;align-items: center">
          <span style="font-size:15px;font-family: 微软雅黑">一、单选题 ({{ paperData.paperInfo.singleNum * 5 }}分)</span>
        </div>
        <!--单选题定位按钮-->
        <div style="width: 100%;display:flex;align-items: start;flex-wrap: wrap;">
          <el-button style=" margin-left: 20px; margin-top:10px ;" plain size="mini" type="primary"
                     v-for="(question, index) of singleList" @click="scrollToSingleList(index)">
            {{ index + 1 }}
          </el-button>
        </div>
      </div>


      <!--多选题标题-->
      <div v-if="multiList.length!=0">
        <div style="margin-left:20px;width: 100%; height: 40px; display: flex;align-items: center;margin-top: 40px">
          <span style="font-size:15px;font-family: 微软雅黑">二、多选题 ({{ paperData.paperInfo.multipleNum * 5 }}分)</span>
        </div>
        <!--多选题定位按钮-->
        <div style="width: 100%;display:flex;align-items: start;flex-wrap: wrap">
          <el-button style=" margin-left: 20px; margin-top:10px ;" plain size="mini" type="primary"
                     v-for="(question, index) of multiList" @click="scrollToMultiList(index)">
            {{ index + 1 }}
          </el-button>
        </div>
      </div>

      <!--填空题标题-->
      <div v-if="fillInList.length!=0">
        <div style="margin-left:20px;width: 100%; height: 40px; display: flex;align-items: center;margin-top: 40px">
          <span style="font-size:15px;font-family: 微软雅黑">三、填空题 ({{ paperData.paperInfo.fillInNum * 5 }}分)</span>
        </div>
        <!--填空题定位按钮-->
        <div style="width: 100%;display:flex;align-items: start;flex-wrap: wrap">
          <el-button style=" margin-left: 20px; margin-top:10px ;" plain size="mini" type="primary"
                     v-for="(question, index) of fillInList" @click="scrollToFillInList(index)">
            {{ index + 1 }}
          </el-button>
        </div>
      </div>

      <!--简答题-->
      <div v-if="textList.length!=0">
        <div style="margin-left:20px;width: 100%; height: 40px; display: flex;align-items: center;margin-top: 40px"><span
            style="font-size:15px;font-family: 微软雅黑">四、简答题 ({{ paperData.paperInfo.textNum * 5 }}分)</span></div>
        <div style="width: 100%;display:flex;align-items: start;flex-wrap: wrap">
          <el-button style=" margin-left: 20px; margin-top:10px ;" plain size="mini" type="primary"
                     v-for="(question, index) of textList" @click="scrollToTextList(index)">
            {{ index + 1 }}
          </el-button>
        </div>
      </div>


      <div style="height: 50px;margin-top: 20px">

        <el-button @click="savePaperData" type="primary" plain size="medium">保存</el-button>
        <el-button @click="test" type="primary" size="medium">提交</el-button>

      </div>
      <!--      <el-button></el-button>-->
    </div>
    <div style="height: 200px"></div>
  </div>
</template>

<script>


import {findByPaperIdStuApi} from "@/api/paper";
import {findByExamIdForStuApi} from "@/api/Exam";
//使用本地仓库存储参数
import {Storage} from '@/utils/localStorage'
import Session_Storage from '@/utils/sessionStorage'

const storage = new Storage();
import {saveAnswerPaperApi} from "@/api/AnswerPaper";
import notification from "@/utils/notification";

export default {
  props: {
    info: {}
  },
  name: "PaperViewStu",
  data() {
    return {
      // paperId: '',
      //接收该试卷的测验数据
      // examId: '',
      //接收试卷的试题数据
      paperData: [],
      examData: [],
      examDataEndTime: '',
      singleList: [],
      multiList: [],
      fillInList: [],
      textList: [],
      preChoice: ['A', 'B', 'C', 'D'],

      //倒计时的样式
      valueStyle: {
        fontSize: '16px',
        color: '#409EFF',
        marginTop: "2px"
      },
      infoData: {}
    }
  },
  methods: {
    async test() {
      console.info("singleList", this.singleList)
      console.info("multiList", this.multiList)
      console.info("fillInList", this.fillInList)
      console.info("textList", this.textList)
      console.info("paperData", this.paperData)
      console.info("examData", this.examData)

      // 定义一个新列表，保存处理后的答案
      const newMultiList = this.multiList.map((question) => {
        // 判断当前题目的类型是否为多选题

        // 将字符串数组拼接成一个字符串
        const selected = question.selected.join(",");
        // 返回新的题目对象，将 selected 字段替换为逗号分隔的单字符串
        return {...question, selected};

      });
      const newFillInList = this.fillInList.map((question) => {
        // 判断当前题目的类型是否为多选题

        // 将字符串数组拼接成一个字符串
        const selected = question.selected.join(",");
        // 返回新的题目对象，将 selected 字段替换为逗号分隔的单字符串
        return {...question, selected};

      });
      console.info("newFillInList", newFillInList)

      const answerPaperData = {
        user: storage.getItem("user"),
        paperData: this.paperData,
        examData: this.examData,
        singleList: this.singleList,
        multiList: newMultiList,
        fillInList: newFillInList,
        textList: this.textList
      }
      let confirm = await this.$myConfirm("提交后不可编辑答卷，确认操作？")
      if (confirm) {
        saveAnswerPaperApi(answerPaperData).then(res => {
          if (res.data.code == 200) {
            // console.info("res.data.data", res.data.data)
            notification.ntfCommonSuccess("提示", res.data.msg);
            console.info("res", res)
            this.$router.push({name: 'AnswerListStuView'})
          }
        })
      }
      // console.info("this.object",this.object)

    },
    savePaperData() {
      console.info("singleList", this.singleList)
      console.info("multiList", this.multiList)
      console.info("fillInList", this.fillInList)
      console.info("textList", this.textList)
      const doneQuestions = {
        singleList: this.singleList.map(question => ({id: question.id, selected: question.selected})),
        multiList: this.multiList.map(question => ({id: question.id, selected: question.selected})),
        fillInList: this.fillInList.map(question => ({id: question.id, selected: question.selected})),
        textList: this.textList.map(question => ({id: question.id, selected: question.selected}))
      };
      console.info("doneQuestions", doneQuestions)
      storage.setItem({name: 'doneQuestions', value: doneQuestions});
      notification.ntfCommonSuccess("提示", "试题保存成功!");

    },
    scrollToSingleList(index) {
      const questionElem = this.$el.querySelectorAll('.singleList')[index]
      questionElem.scrollIntoView({behavior: 'smooth'}) // 平滑滚动到对应singleList题目位置
    },
    scrollToMultiList(index) {
      const questionElem = this.$el.querySelectorAll('.multiList')[index]
      questionElem.scrollIntoView({behavior: 'smooth'}) // 平滑滚动到对应multiList题目位置
    },
    scrollToFillInList(index) {
      const questionElem = this.$el.querySelectorAll('.fillInList')[index]
      questionElem.scrollIntoView({behavior: 'smooth'}) // 平滑滚动到对应fillInList题目位置
    },
    scrollToTextList(index) {
      const questionElem = this.$el.querySelectorAll('.textList')[index]
      questionElem.scrollIntoView({behavior: 'smooth'}) // 平滑滚动到对应fillInList题目位置
    },
    // 将题目数据 附带上选项信息
    getQuestionsIndex() {
      const doneQuestions = JSON.parse(localStorage.getItem('doneQuestions')) || {};
      // console.info("doneQuestions",doneQuestions)

      this.singleList = this.paperData.paperQuestionList.filter(question => question.questionType === '1').map((question, index) => {
        // 为每一道单选题添加 selected 属性，默认值为 -1
        return {...question, selected: ""}
      });
      //多选题
      this.multiList = this.paperData.paperQuestionList.filter(question => question.questionType === '2').map((question, index) => {
        return {...question, selected: []};
      });
      //填空题
      this.fillInList = this.paperData.paperQuestionList.filter(question => question.questionType === '3').map((question, index) => {
        return {...question, selected: []};
      });
      //简答题
      this.textList = this.paperData.paperQuestionList.filter(question => question.questionType === '4').map((question, index) => {
        return {...question, selected: ""};
      });

      if (doneQuestions && Object.keys(doneQuestions).length > 0) {
        // ... 更新题目答案信息
        this.singleList.forEach(question => {
          question.selected = doneQuestions.singleList.find(doneQuestion => doneQuestion.id === question.id)?.selected;
        });
        this.multiList.forEach(question => {
          question.selected = doneQuestions.multiList.find(doneQuestion => doneQuestion.id === question.id)?.selected;
        });
        this.fillInList.forEach(question => {
          question.selected = doneQuestions.fillInList.find(doneQuestion => doneQuestion.id === question.id)?.selected;
        });
        this.textList.forEach(question => {
          question.selected = doneQuestions.textList.find(doneQuestion => doneQuestion.id === question.id)?.selected;
        });
      }


    },
    //获取试卷及其所有试题信息
    getPaperData() {

      findByPaperIdStuApi({id: this.infoData.paperId}).then(res => {
        if (res.data.code === 200) {
          this.paperData = res.data.data;
          //获取到数据之后再进行处理
          this.getQuestionsIndex()
          console.info("fillInList", this.fillInList)
          console.info("multiList", this.multiList)
        }
      })
    },
    //获取测验的数据信息 用于头部
    getExamData() {

      findByExamIdForStuApi({id: this.infoData.examId}).then(res => {
        if (res.data.code == 200) {
          // console.info("res.data.data", res.data.data)
          this.examData = res.data.data;
          this.examDataEndTime = this.examData.endTime;
          // console.info("this.examData",  this.examData)
        }
      })
    },
    sessionCache() {
      const infoFromStorage = Session_Storage.getItem('info');

      console.info("info", this.info)
      console.info("$route", this.$route)
      if (infoFromStorage) {
        this.infoData = infoFromStorage;
      } else {
        this.infoData = this.info;
        Session_Storage.setItem("info", this.info)
      }
    },

  },

  created() {
    this.sessionCache()
    this.getPaperData()
    //查当前测验所有数据
    this.getExamData()
  },
  beforeDestroy() {
    Session_Storage.clear();
    storage.removeItem("doneQuestions");
  }


}
</script>

<style scoped>






.examList-head {
  height: 140px;
  border-bottom: 1px solid #F2F2F2;
}

.head {
//position: fixed; top: 0; height: 50px; background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-family: 微软雅黑;
  color: #75757b;
  width: 100%;

}

.examList {
  margin-top: 32px;
  margin-left: 292px;
  background-color: #ffffff;
  width: 992px;
  border-radius: 10px;
}

.examMenu {
  position: fixed;
  background-color: #ffffff;
  width: 309px;
  top: 90px;
  border-radius: 10px;
  right: 290px;
  z-index: 100;
}

</style>

<style>
.input_bottom input {
  border: none !important;
  border-bottom: 1px solid #ccc !important;
  border-radius: 0 !important;
  width: 220px!important;
}
</style>